package com.raja.servingStation.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.raja.servingStation.common.constant.Constants;
import io.jsonwebtoken.*;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dell on 2017/4/13.
 */

@Component
public class JwtUtil {
    private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);

    private static final String type = "jwt";
    private static final String alg = SignatureAlgorithm.HS256.getValue();
    private static final String audience = "yajun";

    @Value("${spring.profiles.active}")
    private String profiles;

    /**
     * 由字符串生成加密key
     * @return
     */
    public SecretKey generalKey(){
        String stringKey = profiles + Constants.JWT_SECRET;
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 创建jwt
     * @param id 不是必须
     * @param subject 自定义的数据
     * @param ttlMillis 保持回话的时间
     * @return
     * @throws Exception
     */
    public String createJWT(String id, String subject, long ttlMillis){
        try {
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
            long nowMillis = System.currentTimeMillis();
            Date now = new Date(nowMillis);
            SecretKey key = generalKey();
            Map<String, Object> headerMap = getHeaderMap();
            JwtBuilder builder = Jwts.builder()
                    .setId(id)
                    .setIssuedAt(now)   //签发时间
                    .setSubject(subject) //我们的参数或者返回数据
                    .setAudience(audience) //接收方
                    .setHeader(headerMap)
                    .signWith(signatureAlgorithm,key);//签名
            if (ttlMillis >= 0) {
                long expMillis = nowMillis + ttlMillis;
                Date exp = new Date(expMillis);
                builder.setExpiration(exp); // 保持回话时间
            }
            return builder.compact();
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
       return null;
    }

    /**
     * 获取请求头部类型，header
     * @return
     */
    private Map<String, Object> getHeaderMap() {
        Map<String,Object> headerMap =new HashMap<>();
        headerMap.put("type",type);
        headerMap.put("alg",alg);
        return headerMap;
    }

    /**
     * 解密jwt
     * @param jwt
     * @return
     * @throws Exception
     */
    public Claims parseBodyJWT(String jwt) throws Exception{
        SecretKey key = generalKey();
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt).getBody();
        return claims;
    }
    /**
     * 解密jwt
     * @param jwt
     * @return
     * @throws Exception
     */
    public JwsHeader parseHeaderJWT(String jwt) throws Exception{
        SecretKey key = generalKey();
        JwsHeader header = Jwts.parser()
                .setSigningKey(key).parseClaimsJws(jwt).getHeader();
        return header;
    }

    /**
     * 生成subject信息
     * @param jsonObject
     * @return
     */
    public static String generalSubject(JSONObject jsonObject){
        return jsonObject.toJSONString();
    }
    /**
     * 生成subject信息
     * @param object 对象
     * @return
     */
    public static String generalSubject(Object object){
        return  JSONObject.toJSON(object).toString();
    }
    /**
     * 生成subject信息
     * @param list list对象
     * @return
     */
    public static String generalSubject(List list){
        return JSONArray.toJSON(list).toString();
    }
    /**
     * 生成subject信息
     * @param jsonArray json数组
     * @return
     */
    public static String generalSubject(JSONArray jsonArray){
        return jsonArray.toJSONString();
    }

    /**
     * 判断token是否失效
     * @param claims
     * @return true 有效  false 无效
     */
    public static boolean isTokenInvaild(Claims claims){
        long time = claims.getIssuedAt().getTime() + claims.getExpiration().getTime();
        if(time > System.currentTimeMillis()){
            return true;
        }else {
            return  false;
        }
    }
}
